package cn.com.zcode.user.control;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import cn.com.zcode.core.control.BaseActionSupport;
import cn.com.zcode.core.util.StringUtil;
import cn.com.zcode.email.service.EmailService;
import cn.com.zcode.user.model.NoticMessage;
import cn.com.zcode.user.model.User;
import cn.com.zcode.user.service.UserService;

public class NoticeAction extends BaseActionSupport<UserService> {
	private static final Logger logger = Logger.getLogger(NoticeAction.class);
	private static final long serialVersionUID = 1L;
	private String[] users;
	private EmailService emailService;
	private NoticMessage message;
	private boolean noticTegether;

	public boolean isEmail(String str) {
		return str != null && str.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
	}

	public String noticeByEmail() {
		List<User> userlist = this.service.listAllUsers();
		this.addAttribute("userList", userlist);
		if (users == null) {
			return INPUT;
		} else {
			List<User> list = this.service.findUsers(users);
			StringBuffer cc = null;
			List<User> sucUser = new ArrayList<User>();
			for (User user : list) {
				String email = user.getEmail();
				if (isEmail(email)) {
					if (noticTegether) {
						cc = StringUtil.append(cc, email, ",");
						sucUser.add(user);
					} else {
						try {
							boolean boo = emailService.send(email, null, message.getTitle(), message.getContext());
							if(boo){
								sucUser.add(user);
							}
						} catch (Exception e) {
							e.printStackTrace();
							logger.error(e);
						}

					}
				}

			}
			if (noticTegether && cc != null) {
				boolean boo = false;
				try {
					  boo = emailService.send(cc.toString(), null, message.getTitle(), message.getContext());
				} catch (Exception e) {
					e.printStackTrace();
					logger.error(e);
				}
				if(!boo){
					sucUser.clear();
				}
			}
			this.addAttribute("noticedUsers", sucUser);
			return SUCCESS;
		}
	}

	public String[] getUsers() {
		return users;
	}

	public void setUsers(String[] users) {
		this.users = users;
	}

	public EmailService getEmailService() {
		return emailService;
	}

	public void setEmailService(EmailService emailService) {
		this.emailService = emailService;
	}

	public NoticMessage getMessage() {
		return message;
	}

	public void setMessage(NoticMessage message) {
		this.message = message;
	}

	public boolean isNoticTegether() {
		return noticTegether;
	}

	public void setNoticTegether(boolean noticTegether) {
		this.noticTegether = noticTegether;
	}

	public void validateNoticeByEmail() {
		if (users != null && users.length > 0 && (message == null || StringUtil.isEmpty(message.getTitle()) || StringUtil.isEmpty(message.getContext()))) {
			this.addFieldError("message.title", "请输入消息标题");
			this.addFieldError("message.context", "请输入消息内容");
		}
	}

}
